<template>
  <el-form
    :model="form"
    ref="form"
    label-width="100px"
    class="demo-dynamic"
    :rules="rules"
  >
    <el-form-item prop="items.0.email" label="标题">
      <el-input v-model="form.items[0].email"></el-input>
    </el-form-item>
    <div v-for="(item, i) in form.items" :key="i">
      <p>题目{{ i + 1 }}</p>
      <el-form-item
        :prop="`items.${i}.email`"
        label="标题"
        :rules="[
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        ]"
      >
        <el-input v-model="item.email"></el-input>
      </el-form-item>
      <el-form-item
        v-for="(domain, index) in item.domains"
        :label="'答案' + ['A', 'B', 'C', 'D'][index]"
        :key="domain.key"
        :prop="'items.' + i + '.domains.' + index + '.value'"
        :rules="{
          required: true,
          message: '域名不能为空',
          trigger: 'blur',
        }"
      >
        <el-input v-model="domain.value"></el-input>
        <el-button @click.prevent="removeDomain(domain, i)">删除</el-button>
      </el-form-item>
      <el-button @click.prevent="addDomain(i)">添加选项</el-button>
    </div>
    <el-form-item>
      <el-button type="primary" @click="submitForm('form')">提交</el-button>
      <el-button @click="addItem">新增题目</el-button>
      <el-button @click="resetForm('form')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        title: "", // 标题
        aa: {
          title: "", //标题
        },
        items: [
          {
            email: "",
            domains: [
              {
                value: "",
              },
            ],
          },
        ],
      },
      rules: {
        "items.0.email": [
          { required: true, message: "请输入标题", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addItem() {
      this.form.items.push({
        email: "",
        domains: [
          {
            value: "",
            key: Date.now(),
          },
        ],
      });
    },
    removeDomain(item, i) {
      var index = this.form.items[i].domains.indexOf(item);
      if (index !== -1) {
        this.form.items[i].domains.splice(index, 1);
      }
    },
    addDomain(i) {
      this.form.items[i].domains.push({
        value: "",
        key: Date.now(),
      });
    },
  },
};
</script>

<style lang="less" scoped>
</style>